package tv.youxing.android.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.http.VolleyError;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.FollowModel;
import tv.youxing.android.entity.UserInfoModel;
import tv.youxing.android.fragment.DynamicDetailsFragment_one;
import tv.youxing.android.fragment.DynamicDetails_two;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;
import tv.youxing.android.widget.StatusBar.StatusBarCompat;

import static com.mob.MobSDK.getContext;

/**
 * 用户详情
 */
public class DynamicDetailsActivity_new extends AppCompatActivity {


    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.name)
    TextView tvname;
    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.vp)
    ViewPager mViewpager;
    @BindView(R.id.tv_gz_fs)
    TextView tv_gz_fs;//关注粉

    //关注框
    @BindView(R.id.ll_guanzhu)
    LinearLayout ll_guanzhu;
    @BindView(R.id.guanzhu)
    ImageView tv_guanzhu;


    boolean isFollow = false;

    private List<String> mTitle;
    private List<Fragment> mFragment;
    private UserInfoModel mAllData;

    int user_id = -1;

    private LoadingDialog mLoadingDialog;
    private KProgressHUD hud;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        //全屏沉侵式状态栏
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !UtilTools.checkDeviceHasNavigationBar(this)) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                    hideNavigationBar();
//
        }
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.color_black));
        setContentView(R.layout.activity_dynmic_details_new);
        ButterKnife.bind(this);

        this.user_id = Integer.parseInt(getIntent().getStringExtra("user_id"));
        showDialog(this, true);
        loadData(user_id);
    }



    boolean isStateShow=true;
    private void hideNavigationBar() {
        final View decorView = getWindow().getDecorView();
//        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;


        final int flags =
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        decorView.setSystemUiVisibility(flags);
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    if (isStateShow) {
                        decorView.setSystemUiVisibility(flags);
                        isStateShow=false;
                    }
                }
            }
        });
    }

    public void loadData(int user_id) {
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("user_id", user_id);

        RxVolley.post(StaticClass.UserInfoURL, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mAllData = GsonUtils.GsonToBean(t, UserInfoModel.class);
                if (mAllData.getCode() == AppConst.TOKENERROR) {
                    DynamicDetailsActivity_new.this.startActivity(new Intent(DynamicDetailsActivity_new.this,LoginActivity.class));
                    return;
                }

                initHead();
                showDialog(DynamicDetailsActivity_new.this, false);
                initTabLayout();
            }
        });
    }


    void initHead() {
        PicassoUtils.loadImageView(this, mAllData.getResult().getUser_info().getAvatar(), ivHead);
        tvname.setText(mAllData.getResult().getUser_info().getUsername());
        // 关注 165 | 粉丝
        // 165

        tv_gz_fs.setText("关注  " + mAllData.getResult().getUser_info()
                .getFollow_count() + " |  粉丝" + mAllData.getResult().getUser_info().getFans_count());

        mToolbar.setTitle(mAllData.getResult().getUser_info().getUsername());
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        if (mAllData.getResult().getIs_current_user() == 1) {
            ll_guanzhu.setVisibility(View.GONE);
        } else {
            if (mAllData.getResult().getIs_follow() == 1) {
                isFollow = true;
                tv_guanzhu.setImageResource(R.drawable.icon_quxiaofuanzhu);
            } else {
                isFollow = false;
                tv_guanzhu.setImageResource(R.drawable.icon_focus_pre2);
            }
        }
    }

    void initTabLayout() {
        mTitle = new ArrayList<>();
        mTitle.add("动态");
        mTitle.add("关于 TA");

        mFragment = new ArrayList<>();
        mFragment.add(new DynamicDetailsFragment_one(user_id));
        mFragment.add(new DynamicDetails_two(mAllData));

        mViewpager.setOffscreenPageLimit(mFragment.size());

        mViewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle.get(position);
            }

        });

        mTabLayout.setupWithViewPager(mViewpager);
    }


    @OnClick({R.id.iv_back, R.id.guanzhu})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.guanzhu:

                if (UtilTools.LoginJudge()) {
                    guanzhu();
                }


                break;
        }
    }


    void guanzhu() {
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("follow_user_id", mAllData.getResult().getUser_info().getUser_id());


        L.d("follow_user_id:" + mAllData.getResult().getUser_info().getUser_id());
        showProgress("加载中");

        RxVolley.post(StaticClass.GuanZhu, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                FollowModel dianZhanModel = GsonUtils.GsonToBean(t, FollowModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    DynamicDetailsActivity_new.this.startActivity(new Intent(DynamicDetailsActivity_new.this,LoginActivity.class));
                    return;
                }

                CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                if (dianZhanModel.getCode() == 200) {
                    CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                    System.out.println(t);
                    if (dianZhanModel.getResult().getIs_follow() == 1) {
                        tv_guanzhu.setImageResource(R.drawable.icon_quxiaofuanzhu);
                    } else {
                        tv_guanzhu.setImageResource(R.drawable.icon_focus_pre2);
                    }
                }
                hideProgress();
            }

            @Override
            public void onFailure(VolleyError error) {
                super.onFailure(error);
                hideProgress();
            }
        });
    }


    protected void showDialog(Activity activity, boolean isShow) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(activity);
        }
        if (mLoadingDialog != null) {
            mLoadingDialog.setLoadingText("加载中")
                    .setSuccessText("加载成功")//显示加载成功时的文字
                    //.setFailedText("加载失败")
                    .setInterceptBack(true)
                    .setLoadSpeed(LoadingDialog.Speed.SPEED_TWO)
                    .setRepeatCount(1);
        }
        if (isShow) {
            mLoadingDialog.show();
        } else {
            mLoadingDialog.close();
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void showProgress(String message) {
        if (hud == null) {
            hud = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel(message)
                    .setCancellable(true);
        }
        if (!hud.isShowing()) {
            hud.show();
        }
    }

    public void hideProgress() {
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
        }
    }

}